
module WindowNewCustomer
(
    newCustomerWindow -- :: IORef CustomersDB -> ComboBox -> IO ()
) 
where

import Graphics.UI.Gtk
import Data.IORef
import Customer
import MainHandler

newCustomerWindow :: IORef MainHandler -> ComboBoxEntry -> IO ()
newCustomerWindow cdb combo = do 
  initGUI
  window <- windowNew
  windowSetDefaultSize window 150 150
  windowSetPosition window WinPosCenter
  windowSetTitle window "Nuevo cliente"
  
  
  
  hbox <- vBoxNew True 5
  entryName <- labelNew (Just "Nombre de Cliente Nuevo:")
  entry <- entryNew
  
  buttonCtm <- buttonNewWithLabel "Agregar cliente"
  buttonCtm `onClicked` addNewCustomer cdb entry combo (Just window)
  
  set window [windowDefaultWidth := 150, windowDefaultHeight := 150,
              containerBorderWidth := 10, containerChild := hbox]
              
  boxPackStart hbox entryName PackNatural 0                 
  boxPackStart hbox entry PackNatural 0            
  boxPackStart hbox buttonCtm PackNatural 0
  
  
  widgetShowAll window
 
----------------------------------------------------------------------------------------
-----------------FUNCIONES PARA ACCIONES------------------------------------------------
----------------------------------------------------------------------------------------

addNewCustomer cdb entry combo win = do
    txt <- entryGetText entry
                        
    modifyIORef cdb (refAddCustomer txt)
    datos <- readIORef cdb
    putStr (show (length (getCustomers datos)))
    
    addMsg <- messageDialogNew win [DialogDestroyWithParent] MessageInfo ButtonsOk "Cliente agregado"
    dialogRun addMsg
    
    let w = case win of 
                (Just x) -> x
    widgetDestroy w
    updateCombo combo cdb
    return ()
    
refAddCustomer :: String -> MainHandler -> MainHandler
refAddCustomer name cdb = addCustomerToHandler cdb (createCustomer name)

updateCombo combo db = do
    customers <- readIORef db
    store <- listStoreNew (getCustomers customers)
    comboBoxSetModel combo (Just store)
    customStoreSetColumn store textColumn (getCustomerName)
    
textColumn :: ColumnId Customer String
textColumn = makeColumnIdString 0